package o2o.thridpost.dada.controller;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.ValidateUtil;
import lombok.extern.slf4j.Slf4j;
import o2o.config.PropConfigure;
import o2o.config.redis.RedisManager;
import o2o.config.thirdpost.dada.DadaRequestClient;
import o2o.thridpost.dada.client.DadaApiResponse;
import o2o.thridpost.dada.client.DadaRequestParam;
import o2o.thridpost.dada.config.UrlConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static o2o.config.redis.RedisKeyConstant.DADA_CITY_NAME_CODE;

/**
 * 达达城市接口
 *
 * @author sunyufan deporation@qq.com
 * @date 2021/5/28 15:11
 * @description: DadaCityController
 */
@RequestMapping("/dada/city")
@RestController
@Slf4j
public class DadaCityController {

    @Autowired
    private DadaRequestClient requestClient;

    @RequestMapping(value = "/cityCode", method = RequestMethod.GET)
    public String queryCityCode(@RequestParam("cityName") String cityName) {

        Object cache = RedisManager.get(DADA_CITY_NAME_CODE);

        if (ValidateUtil.isNull(cache)) {
            DadaRequestParam<String> requestParam = new DadaRequestParam<>("", requestClient.getAppConfig());

            DadaApiResponse apiResponse = requestClient.callRpc(requestParam, UrlConstant.CITY_CODE_URL);

            log.info(apiResponse.toString());

            if (apiResponse.getCode() == 0) {

                List<Map<String, String>> result = (List<Map<String, String>>) apiResponse.getResult();

                Map<String, String> cityMap = new HashMap<>(result.size());

                result.forEach(
                        e -> {
                            cityMap.put(e.get("cityName"), e.get("cityCode"));
                        }
                );

                log.info("转换结果" + cityMap);

                RedisManager.set(DADA_CITY_NAME_CODE, cityMap);

                Map<String, Object> res = new HashMap<>(1);

                res.put("city_code", cityMap.get(cityName.trim()));

                return AjaxResult.successResult(res);
            } else {
                return AjaxResult.errorResult("msg", apiResponse.getMsg());
            }
        } else {

            Map<String, String> cityMap = (Map<String, String>) cache;

            log.info(cityMap.toString());

            Map<String, Object> res = new HashMap<>(1);

            res.put("city_code", cityMap.get(cityName.trim()));

            return AjaxResult.successResult(res);

        }


    }

}
